package com.trendata.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.trendata.domain.wechat.Config;
import com.trendata.service.CacheService;
import com.trendata.service.UserService;
import com.trendata.service.wechat.WechatService;
import com.trendata.util.JsonResult;
import com.trendata.util.SignUtil;
import com.trendata.util.TimeUtil;

/**
 * 微信消息处理
 * 
 * @author: HuangXiuXiu Email:243559392@qq.com
 */
@Controller
@RequestMapping("/wechat")
public class WeChatController {
	private static Logger logger = Logger.getLogger("wechatLogger");
	@Autowired
	private UserService userService;
	@Autowired
	private WechatService weChatService;
	@Autowired
	private CacheService cacheService;

	/**
	 * 微信核心处理，微信会将所有请求发到这个接口，如果对名称进行修改，需要到微信公众平台-开发者中心-服务器配置-修改配置-url修改。
	 * <p>
	 * url=/wechat/coreServlet.do
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/coreServlet")
	@ResponseBody
	public void coreServlet(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 微信的验证将通过get方式传送
			if (request.getMethod().equals("GET")) {
				// 微信加密签名
				String signature = request.getParameter("signature");
				// 时间戳
				String timestamp = request.getParameter("timestamp");
				// 随机数
				String nonce = request.getParameter("nonce");
				// 随机字符串
				String echostr = request.getParameter("echostr");
				PrintWriter out = response.getWriter();
				// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
				if (SignUtil.checkSignature(signature, timestamp, nonce)) {
					out.print(echostr);
				}
				out.close();
				out = null;
			}
			// 调用核心业务类接收消息、处理消息，将用post方式传送
			else if (request.getMethod().equals("POST")) {
				// 对接收到的消息进行处理
				String respMessage = weChatService.processRequest(request);
				// 响应消息
				PrintWriter out = response.getWriter();
				out.print(respMessage);
				out.close();
			}
		} catch (IOException e) {
			logger.error("微信转发请求时出现异常:" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 获取对微信jssdk的验证配置。需要传入使用页面的url地址，无需转码
	 * 
	 * <p>
	 * url =/wechat/getWXConfig.do?url=
	 * </p>
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/getWXConfig")
	@ResponseBody
	public String getAccessToken(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		String url = request.getParameter("url");
		String openId = request.getParameter("openId");
		if (url == null || url.equals("")) {
			return result.setMessage("url地址不符合规范").toJsonString();
		}
		// 有机会最好改成url解码
		if (openId != null && !openId.equals("")) {
			url = url + "&openId=" + openId;
		}
		String jsTicket = cacheService.getJSTicket(TimeUtil.getCurrentHour());
		Config config = SignUtil.getSignature(url, jsTicket);
		result.setValue(config);
		result.setSuccess(true);
		return result.toJsonString();
	}

}
